package cn.elwy.rcp.ui.table.format;

import cn.elwy.common.util.ConvertTypeUtil;

public class BooleanFormat extends ColumnFormat {

  private static final String[] DEFAULT_PATTERN = { "是", "否" };
  private static final long serialVersionUID = 1L;

  public BooleanFormat() {
  }

  public BooleanFormat(String pattern) {
    super(pattern);
  }

  @Override
  public String format(Object value) {
    if (value == null) {
      return "";
    }
    String[] formatPattern = getFormatPattern();
    if (value instanceof Boolean) {
      if ((Boolean) value == true) {
        return formatPattern[0].trim();
      } else {
        return formatPattern[1].trim();
      }
    } else {
      boolean result = ConvertTypeUtil.toBoolean(value.toString());
      if (result) {
        return formatPattern[0].trim();
      } else {
        return formatPattern[1].trim();
      }
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public <T> T parse(String value, Class<T> clazz) {
    String[] formatPattern = getFormatPattern();
    if (value == null) {
      return (T) Boolean.FALSE;
    } else if (formatPattern[0].trim().equals(value.trim())) {
      return (T) Boolean.TRUE;
    } else {
      return (T) Boolean.FALSE;
    }
  }

  private String[] getFormatPattern() {
    String pattern = getPattern();
    if (pattern == null) {
      return DEFAULT_PATTERN;
    }
    String[] patterns = pattern.split(",");
    if (patterns.length == 2) {
      return patterns;
    }
    return DEFAULT_PATTERN;
  }

}
